package org.mech.sefer.client.i18n;

import java.util.ArrayList;
import java.util.List;

import org.mech.sefer.client.i18n.I18nAware;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * The I18nAwareRegisterProcessor register all I18nAware interfaces
 * </p>
 * <p>
 * Date: 2.5.2012 15:42:39
 * </p>
 * 
 * @author martin.krajc
 */
@Component("i18nAwareProcessor")
public class I18nAwareRegisterProcessor implements BeanPostProcessor {

	private List<I18nAware> i18nAwares = new ArrayList<I18nAware>();
	private I18n i18n;

	@Override
	public Object postProcessAfterInitialization(Object obj, String name)
			throws BeansException {
		if (obj instanceof I18nAware) {
			final I18nAware awareObject = (I18nAware) obj;
			
			//add to aware objects
			i18nAwares.add(awareObject);
			
			if (i18n != null) {
				// if something is set just propagate to this object
				awareObject.setI18n(i18n);
			}

		}
		return obj;

	}

	@Override
	public Object postProcessBeforeInitialization(Object object, String arg1)
			throws BeansException {
		return object;
	}

	public void propagate(final I18n i18n) {
		this.i18n = i18n;
		
		for (I18nAware aware : i18nAwares) {
			aware.setI18n(i18n);
		}
		
	}

}
